let socketTask = null;
let heartbeatTimer = null;
let reconnectTimer = null;
const WS_URL = 'wss://xiaolanghua.zhanyuankj.cn/wss'; // 替换为实际地址

export function initSocket(userId, token) {
	if (socketTask && socketTask.readyState === 1) return;

	// 关闭旧连接
	if (socketTask) {
		socketTask.close({
			success: () => console.log('WebSocket连接已关闭')
		});
		clearInterval(heartbeatTimer);
		clearTimeout(reconnectTimer);
	}

	// 创建新连接
	socketTask = uni.connectSocket({
		url: WS_URL,
		success: () => console.log('WebSocket连接创建成功'),
		fail: (err) => {
			console.error('WebSocket连接失败', err);
			scheduleReconnect();
		}
	});

	// 监听事件
	socketTask.onOpen(() => {
		console.log('WebSocket已打开');
		startHeartbeat();
		sendAuthMessage(userId, token);
	});

	socketTask.onMessage((res) => {
		handleMessage(res.data);
	});

	socketTask.onError((err) => {
		console.error('WebSocket错误', err);
		scheduleReconnect();
	});

	socketTask.onClose(() => {
		console.log('WebSocket已关闭');
		stopHeartbeat();
		scheduleReconnect();
	});
}

function sendAuthMessage(userId, token) {
	sendSocketMessage({
		type: 'auth',
		user_id: userId,
		token: token
	});
}

function handleMessage(data) {
	try {
		console.log('收到消息:', data);
		const message = JSON.parse(data);
		console.log('收到消息:', message);

		// 根据消息类型分发处理
		switch (message.type) {
			case 'auth_success':
				uni.$emit('auth_success');
				break;
			case 'queue_joined':
				uni.$emit('queue_joined');
				break;
			case 'match_success':
				uni.$emit('match_success', {
					matchId: message.room_id,
					opponent: message.opponent
				});
				break;
			case 'game_start':
				uni.$emit('game_start', {
					matchId: message.room_id,
					totalQuestions: message.total_questions
				});
				break;
			case 'new_question':
				uni.$emit('new_question', {
					matchId: message.room_id,
					question: message.question,
					timeLimit: message.time_limit,
					current: message.current_question_index,
					totalQuestions: message.total_questions
				});
				break;
			case 'question_timeout':
				uni.$emit('question_timeout', {
					matchId: message.room_id,
					question: message.question,
					yourScore: message.your_score,
				});
				break;
			case 'answer_received':
				uni.$emit('answer_received', {
					questionId: message.question_id
				});
				break;
			case 'opponent_answered':
				uni.$emit('opponent_answered', {
					opponentScore: message.opponent_score,
					matchId: message.room_id,
				});
				break;
			case 'question_result':
				uni.$emit('question_result', {
					matchId: message.room_id,
					yourAnswer: message.your_answer,
					yourScore: message.your_score,
					correct:message.correct,
					correctAnswer: message.correct_answer
				});
				break;
			case 'game_end':
				uni.$emit('game_end', {
					matchId: message.room_id,
					yourScore: message.total_score,
					answers: message.answers,
					winnerId:message.winner_id,
					suc_num: message.suc_num,
					resultUrl:message.resultUrl
				});
				break;
			case 'error':
			uni.showToast({
				title: message.msg,
				icon: 'none'
			});
			// setTimeout(() => {
			// 	uni.reLaunch({
			// 		url:'/pages/index/index'
			// 	})
			// }, 3000);
			
				break;
		}
	} catch (e) {
		console.error('消息解析失败', e);
	}
}

// 发送消息
export function sendSocketMessage(message) {
	console.log(socketTask?.readyState)
	if (socketTask?.readyState === 1) {
		socketTask.send({
			data: JSON.stringify(message),
			success: () => console.log('消息发送成功'),
			fail: (err) => console.error('消息发送失败', err)
		});
	}
}

// 启动心跳
function startHeartbeat() {
	stopHeartbeat();
	heartbeatTimer = setInterval(() => {
		sendSocketMessage({
			type: 'heartbeat'
		});
	}, 25000); // 25秒发送一次心跳
}

// 停止心跳
function stopHeartbeat() {
	if (heartbeatTimer) {
		clearInterval(heartbeatTimer);
		heartbeatTimer = null;
	}
}

// 安排重连
function scheduleReconnect() {
	clearTimeout(reconnectTimer);
	reconnectTimer = setTimeout(() => {
		const userId = uni.getStorageSync('user_id');
		const token = uni.getStorageSync('token');
		if (userId && token) {
			initSocket(userId, token);
		}
	}, 3000);
}

// 关闭WebSocket
export function closeSocket() {
	if (socketTask) {
		socketTask.close();
		socketTask = null;
	}
	stopHeartbeat();
	clearTimeout(reconnectTimer);
}